package com.yjz.designpattern.断路器模式;

public class CircuitBreaker {
    private enum State {
        CLOSED, OPEN, HALF_OPEN
    }

    private State state = State.CLOSED;
    private long lastFailureTime;
    private int failureCount = 0;
    private final int failureThreshold = 3; // 失败阈值
    private final long resetTimeout = 10000; // 10秒后尝试自动恢复(转到半开状态)

    public synchronized boolean call(Runnable action) {
        if (state == State.OPEN) {
            if (System.currentTimeMillis() - lastFailureTime > resetTimeout) {
                state = State.HALF_OPEN;
            } else {
                return false;
            }
        }

        try {
            action.run();
            if (state == State.HALF_OPEN) {
                // 如果在半开状态下请求成功，则重置断路器
                reset();
            }
            return true;
        } catch (Exception e) {
            lastFailureTime = System.currentTimeMillis();
            failureCount++;
            if (failureCount > failureThreshold || state == State.HALF_OPEN) {
                state = State.OPEN;
            }
            return false;
        }
    }

    private void reset() {
        state = State.CLOSED;
        failureCount = 0;
    }

    public static void main(String[] args) {
        CircuitBreaker circuitBreaker = new CircuitBreaker();

        // 模拟请求
        for (int i = 0; i < 10; i++) {
            boolean result = circuitBreaker.call(() -> {
                // 模拟服务调用，可以在这里抛出异常来模拟失败
                if (Math.random() > 0.7) {
                    throw new RuntimeException("Service failure");
                }
                System.out.println("Service call successful");
            });

            if (!result) {
                System.out.println("Service call failed or blocked by circuit breaker");
            }

            // 等待一段时间再发送下一个请求
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}